package cn.initcap.service.impl;

import cn.initcap.dao.OrderInfoMapper;
import cn.initcap.entity.OrderInfo;
import cn.initcap.entity.SeckillOrder;
import cn.initcap.entity.SeckillUser;
import cn.initcap.redis.OrderKey;
import cn.initcap.redis.RedisService;
import cn.initcap.service.OrderService;
import cn.initcap.vo.GoodsVo;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author initcap
 * @date Created in 2018/8/10 PM4:49.
 */
@Service
public class OrderServiceImpl implements OrderService {

    private final OrderInfoMapper orderInfoMapper;
    private final RedisService redisService;

    @Autowired
    public OrderServiceImpl(OrderInfoMapper orderInfoMapper, RedisService redisService) {
        this.orderInfoMapper = orderInfoMapper;
        this.redisService = redisService;
    }

    @Override
    public SeckillOrder getMiaoshaOrderByUserIdGoodsId(long userId, long goodsId) {
        return redisService.get(OrderKey.GET_SECKILL_ORDER_BY_UID_GID, "" + userId + "_" + goodsId, SeckillOrder.class);
    }

    @Override
    public SeckillOrder getSeckillOrderByUserIdGoodsId(long userId, long goodsId) {
        return orderInfoMapper.getSeckillOrderByUserIdGoodsId(userId, goodsId);
    }

    @Override
    public OrderInfo getOrderById(long orderId) {
        return orderInfoMapper.selectByPrimaryKey(orderId);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderInfo createOrder(SeckillUser user, GoodsVo goods) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getSeckillPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderInfoMapper.insert(orderInfo);
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(orderInfo.getId());
        seckillOrder.setUserId(user.getId());
        orderInfoMapper.insertSeckillOrder(seckillOrder);

        redisService.set(OrderKey.GET_SECKILL_ORDER_BY_UID_GID, "" + user.getId() + "_" + goods.getId(), seckillOrder);

        return orderInfo;
    }

    @Override
    public void deleteOrders() {
        orderInfoMapper.deleteOrders();
        orderInfoMapper.deleteSeckillOrders();
    }
}
